<?php
 
class PredictionUser extends User {
	
	public $utakmice;
	public $broj_pogodjenih;

	public $poeni;
	
	public $ukupnoPoena;
	
	// constructor
	
	public function __construct($i = 0) {
		$this->id = $i;
		if ($i != 0) {
			parent::__construct($this->id);
		}
	}
	
	// functions
		
	public function hitNumber(){
			foreach ($this->utakmice as $match_id=>$tip)
			{
				$match = new Match($match_id);
				if ($match->odigrana) {
					if ($match->getWinner() == $tip) {
						$this->broj_pogodjenih++;
					}
				}
			}
	}
	
	public function calculatePoints() {
		$this->ukupnoPoena = $this->broj_pogodjenih * 1;
	}
	
	public function countFinishedTips() {	// pomocna funkcija
		$i=0;
		foreach($this->utakmice as $id => $match) {
			$mec = new Match($id);
			if ($match && $mec->odigrana) {
				$i++;
			}
		}
		return $i;
	}
	
	public function calculatePercentage() {
		if ($this->countFinishedTips()) {
			return (round($this->broj_pogodjenih / $this->countFinishedTips() * 100));
		}
	}
	
	public function getEmptyMatch() {
		$pom_niz = getAllMatches();
		foreach ($pom_niz as $match){
			$this->utakmice[$match->id] = null;
		
		}
	}
	
	public function getTips() {
		$q = "SELECT tip, utakmica FROM prediction WHERE user = ". $this->id;
		$r = mysql_query($q);
		if (mysql_num_rows($r)) {
			while ( $n = mysql_fetch_array($r)) {
				$this->utakmice[$n['utakmica']] = $n['tip'];
			}
		}
	}
	
	//admin
	public function insertTip($id_utakmice, $tip){
		$mec = new Match($id_utakmice);
		if (!$mec->lockPrediction()) {
			if ($this->isTipped($id_utakmice)) {
				$q = "UPDATE prediction SET tip = ". $tip ." WHERE `user` = ".$this->id." AND `utakmica` = " . $id_utakmice;
			}
			else {
				$q = "INSERT INTO prediction(user, utakmica, tip) VALUES ('".$this->id."', '".$id_utakmice."', '".$tip."')";
			}
			$r = mysql_query("set names 'utf8'");
			if (mysql_query($q)) {
				//echo "Tipovali ste. Bravo!";
			}
			else {
				//echo "Neuspesno tipovanje. Probajte ponovo.";
			}
		}
		else {
			//echo "The betting is finished. You cannot bet on this match anymore.";
		}
	}
	
	public function isTipped($id_utakmice){
		if($this->utakmice[$id_utakmice] == null)
			return 0;
		else 
			return 1;
	}
} // end of class PredictionUser


?>